import {NetUtil} from '../../utils/NetUtil'
import {URL} from '../../config/UrlConfig'
import {actions_const, mutations_const} from '../../config/StoreConstant'
import {ConstJsonManager} from '../../utils/ConstJsonManager'
import Cmd from '../../config/Cmd'
import {addDevice} from "../../utils/WebsocketConfig";

const state = {
    hasLogin: false,
    loginMember: {},
    class: {
        info: {},
        member: {},
        teachingAssistant: {},
        device: {
            groupList: [],
            list: []
        },
    }
};

const mutations = {
    RESET_CLASS(state, data) {
        state.class = data
    },
    RESET_LOGIN_MEMBER(state, data) {
        state.loginMember = data
    },
    UPDATE_LOGIN_MEMBER(state, data) {
        state.loginMember = Object.assign(state.loginMember, data)
    },
    UPDATE_CLASS_INFO(state, data) {
        state.class.info = data
    },
    UPDATE_HAS_LOGIN(state, data) {
        state.hasLogin = data
    },
    UPDATE_CLASS_TEACHING_ASSISTANT(state, data) {
        state.class.teachingAssistant = data
    },
    UPDATE_CLASS_MEMBER(state, data) {
        // if(state.class.member.length){
        //   state.class.member = Object.assign(state.class.member, data)
        // }else{
        state.class.member = data
        // }
    },
    UPDATE_CLASS_DEVICE_GROUP_LIST(state, data) {
        state.class.device.groupList = data
    },
    UPDATE_CLASS_DEVICE_LIST(state, data) {
        state.class.device.list = data
    }
}

const actions = {
    someAsyncTask({commit}) {
        // do something async
        commit('INCREMENT_MAIN_COUNTER')
    },
    getLoginMember: function ({commit, state}) {
        return new Promise((resolve, reject) => {
            /***
             * 已经有用户信息
             */
            if (state.loginMember.id) {
                resolve(state.loginMember)
                return
            }

            /****
             * 查询用户信息
             */
            NetUtil.post(URL.teacher.loginInfo, {})
                .then((res) => {
                    commit(mutations_const.UPDATE_LOGIN_MEMBER, res.member)
                    resolve(res.member)
                })
                .catch((res) => {
                    reject(res)
                })
        })
    },
    getClassInfo: function ({commit, state, rootState}) {
        return new Promise((resolve, reject) => {


            if (state.class.info.id) {

                resolve(state.class.info);
                return;
            }
            /****
             * 查询班级信息
             */
            NetUtil.post(URL.class.getClassInfo, {})
                .then((res) => {
                    if (!res) {
                        vueMain.$alert('请使用班级管理员账号登录', '错误提示', {showCancelButton: false, showClose: false})
                            .then(() => {
                                vueMain.$store.commit(mutations_const.RESET_LOGIN_MEMBER, {})
                                vueMain.$store.commit(mutations_const.RESET_CLASS, {
                                    info: {},
                                    member: {},
                                    teachingAssistant: {},
                                    device: {
                                        groupList: [],
                                        list: []
                                    },
                                })
                                Promise.all([
                                    ConstJsonManager.set('token', ''),
                                    // ConstJsonManager.set('autoLogin', false)
                                    ConstJsonManager.set('rememberPass', false)
                                ])
                                    .then(() => {
                                        vueMain.$router.push('/login')
                                    })
                            })
                    } else {
                        NetUtil.post(URL.School.get, {id: res.organizationId})
                            .then((subRes) => {
                                NetUtil.post(URL.PaperInfo.bookTree, {
                                    directoryNode: subRes.businessOrganization.schoolLevel,
                                    len: 3
                                }).then((subjectList) => {
                                    let node = {}
                                    for (let subject of subjectList) {
                                        // console.log(subject)
                                        node[subject.node] = subject
                                    }
                                    Object.assign(res, subRes, {subjectList: node})
                                    commit(mutations_const.UPDATE_CLASS_INFO, res)
                                    resolve(res)
                                })
                            })
                    }
                })
                .catch((res) => {
                    reject(res)
                })
        })
    },
    getClassTeachingAssistant: function ({commit, state, dispatch}) {
        return new Promise((resolve, reject) => {
            /***
             * 已经有教辅信息
             */
            if (state.class.teachingAssistant.init) {
                resolve(state.class.teachingAssistant);
                return
            }

            /****
             * 查询教辅信息
             */

            dispatch(actions_const.GET_CLASS_INFO)
                .then(classRoom => {
                    // console.log(classRoom)
                    return NetUtil.post(URL.teachingAssistant.get, {classId: classRoom.id})
                })
                .then((res) => {
                    let arr = [];
                    for (let temp of res) {
                        arr.push(temp.teachingAssistantId)
                    }
                    NetUtil.post(URL.teachingAssistant.getList, {ids: arr}).then((subRes) => {
                        let node = {init: true};
                        for (let book of subRes) {
                            if (!node.hasOwnProperty(book.subject)) node[book.subject] = {};
                            node[book.subject][book.id] = book;
                        }

                        commit(mutations_const.UPDATE_CLASS_TEACHING_ASSISTANT, node)
                    });
                    resolve(res)
                })
                .catch((res) => {
                    reject(res)
                })
        })
    },
    getClassMember: function ({commit, state, dispatch}) {
        return new Promise((resolve, reject) => {
            /****
             * 查询班级成员信息
             */
            if (state.class.member.init) {
                resolve(state.class.member);
                return;
            }

            dispatch(actions_const.GET_CLASS_INFO)
                .then(res => {

                    return NetUtil.post(URL.class.getClassMember, {classId: state.class.info.id})
                })
                .then((res) => {
                    let members = {};
                    Object.defineProperty(members, 'init', {
                        value: true,
                        writable: true
                    });
                    for (let member of res.members) {
                        if (member.memberType === 1) members[member.memberNumber] = member
                    }
                    commit(mutations_const.UPDATE_CLASS_MEMBER, members, false);
                    resolve(res.members);
                    commit(mutations_const.UPDATE_HAS_LOGIN, true);
                    /*** 添加设备  **/
                    setTimeout(() => {
                        try {
                            addDevice();
                        } catch (e) {
                            console.log(e)
                        }
                    }, 2000);
                })
                .catch((res) => {
                    reject(res)
                })
        })
    },
    getClassDeviceList: function ({commit, state, dispatch}) {

        return new Promise((resolve, reject) => {

            dispatch(actions_const.GET_CLASS_INFO).then(res => {

                return NetUtil.post(URL.class.getClassDeviceGroupList, {classId: state.class.info.id});
            })
                .then(res => {

                    commit(mutations_const.UPDATE_CLASS_DEVICE_GROUP_LIST, res);
                    NetUtil.post(URL.device.list, {deviceGroupId: res[0].deviceGroupId}).then(subRes => {

                        commit(mutations_const.UPDATE_CLASS_DEVICE_LIST, subRes);
                        // console.log(subRes, 'device-list');
                        resolve(subRes)
                    })
                })
        })
    }
}
const getters = {
    getDeviceByMac: state => (mac) => {
        let list = state.class.device.list;
        for (let item of list) {
            // console.log(mac, item.serialNumber);

            if (item.serialNumber.toLowerCase() == mac.toLowerCase()) {
                // console.log('****');
                // console.log(item);
                return item;
            }
        }
        console.log('获取设备列表')
    },
    getMemberByMemberNumber: state => (memberNumber) => {

        for (let id in state.class.member) {

            if (state.class.member[id].memberNumber == memberNumber) {
                return state.class.member[id];
            }
        }
    },
    deviceMacList: state => {

        let macList = []
        let parse = function (str) {
            let res = [];
            if (str.length !== 12) {

                return [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
            }
            for (let i = 0; i < str.length; i += 2) {

                let temp = str.substr(i, 2);
                res.push(eval("0x" + temp))
            }
            return res;
        }
        if (state.class.device.list) {
            console.log(state.class.device.list);
            for (let device of state.class.device.list) {

                macList.push(parse(device.serialNumber))
            }
        }
        return macList
    },
    getMemberByDeviceNum: state => (deviceNum) => {
        return state.class.member[deviceNum]
    },
    getSubjectList(state) {
        return state.class.info.subjectList
    },
    getClassId(state) {
        return state.class.info.id
    },
    getSubjectTeachingAssistant: state => (subject) => {
        return subject ? state.class.teachingAssistant[subject] : []
    },
    getMember: state => (filter) => {
        let arr = []
        if (typeof filter !== 'undefined') {
            for (let subKey in state.class.member) {
                let obj = Object.assign({}, state.class.member[subKey])
                for (let key in filter) {
                    if (state.class.member[subKey].memberId === key) {
                        obj.hasAnswered = filter[key]
                        arr.push(obj)
                        break
                    }
                }
                if (!obj.hasAnswered) {
                    obj.hasAnswered = 0
                    arr.push(obj)
                }
            }
            return arr
        }
        return []
    },
    getAllMember: state => {
        return state.class.member
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}
